package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author luomingliang
 * @since 2022/3/31 22:10
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static DefaultRedisScript<Long> SECKILL_SCRIPT = null;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            String queueName = "stream.orders";
//            while (true) {
//                try {
//                    stringRedisTemplate.opsForStream().
//                    //1.获取队列中的订单信息 XREADGROUP GROUP g1 c1 CONUT 1 BLOCK 2000 STREAMS s1 >
//                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
//                            Consumer.from("g1", "c1"),
//                            StreamReadOptions.empty().count(1L).block(Duration.ofSeconds(2L)),
//                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
//                    );
//                    //2.判断订单信息是否为空
//                    if (CollectionUtil.isEmpty(list)) {
//                        //2.1 如果为null，说明没有消息，继续下次循环
//                        continue;
//                    }
//                    //解析消息
//                    MapRecord<String, Object, Object> recordMap = list.get(0);
//                    Map<Object, Object> value = recordMap.getValue();
//                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
//                    //3.创建订单
//                    createVoucherOrder(voucherOrder);
//                    //4.确认消息 XACK s1 g1 id
//                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", recordMap.getId());
//                } catch (Exception e) {
//                    log.error("处理订单异常", e);
//                    handlePendingList();
//                }
//            }
        }

        //处理pending-list中的订单消息
        private void handlePendingList() {
            String queueName = "stream.orders";
            while (true) {
                try {
                    //1.获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 CONUT 1 BLOCK 2000 STREAMS s1 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1L),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //2.判断订单信息是否为空
                    if (CollectionUtil.isEmpty(list)) {
                        //2.1 如果为null，说明pending-list中没有消息，结束循环
                        break;
                    }
                    //解析消息
                    MapRecord<String, Object, Object> recordMap = list.get(0);
                    Map<Object, Object> value = recordMap.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //3.创建订单
                    createVoucherOrder(voucherOrder);
                    //4.确认消息 XACK s1 g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", recordMap.getId());
                } catch (Exception e) {
                    log.error("处理pending-list订单异常", e);
                    try {
                        Thread.sleep(100L);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                }
            }
        }
    }

//    private final BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
//    private class VoucherOrderHandler implements Runnable {
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    //1.获取队列中的订单信息
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    //2.创建订单
//                    createVoucherOrder(voucherOrder);
//                } catch (InterruptedException e) {
//                    log.error("处理订单异常", e);
//                }
//            }
//        }
//    }

    private void createVoucherOrder(VoucherOrder voucherOrder) {
        Long voucherId = voucherOrder.getVoucherId();
        //5.一人一单
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock redisLock = redissonClient.getLock("lock:order:" + userId);
        //尝试获取锁
        boolean isLock = redisLock.tryLock();
        //判断
        if (!isLock) {
            //获取锁失败，直接返回失败或重试
            log.error("不允许重复下单！");
            return;
        }
        try {
            //5.1 查询该用户是否买过该优惠券
            int count = lambdaQuery()
                    .eq(VoucherOrder::getUserId, userId)
                    .eq(VoucherOrder::getVoucherId, voucherId)
                    .count();
            //5.2 判断是否存在
            if (count > 0) {
                //用户已经购买过了
                log.error("用户已经购买过一次！！");
                return;
            }
            //6.扣减库存
            boolean success = seckillVoucherService.lambdaUpdate()
                    .setSql("stock = stock - 1")
                    .eq(SeckillVoucher::getVoucherId, voucherId)
                    .gt(SeckillVoucher::getStock, 0)
                    .update();
            if (!success) {
                //扣减失败
                log.error("库存不足");
                return;
            }
            //保存入库
            save(voucherOrder);
        } finally {
            //释放锁
            redisLock.unlock();
        }
    }

    @Override
    public Result secKillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId));
        assert result != null;
        int r = result.intValue();
        //2.判断结果是否为0
        if (r != 0) {
            //2.1 不为0，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        //3.返回订单id
        return Result.ok(orderId);
    }

//    @Override
//    public Result secKillVoucher(Long voucherId) {
//        Long userId = UserHolder.getUser().getId();
//        //1.执行lua脚本
//        Long result = stringRedisTemplate.execute(
//                SECKILL_SCRIPT,
//                Collections.emptyList(),
//                voucherId.toString(),
//                userId.toString());
//        assert result != null;
//        int r = result.intValue();
//        //2.判断结果是否为0
//        if (r != 0) {
//            //2.1 不为0，代表没有购买资格
//            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
//        }
//        //2.2 为0，有购买资格，把下单信息保存到阻塞队列
//        //TODO 保存至阻塞队列
//        //2.3 创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //2.4 订单id
//        long orderId = redisIdWorker.nextId("order");
//        voucherOrder.setId(orderId);
//        //2.5 用户id
//        voucherOrder.setUserId(userId);
//        //2.6 代金券id
//        voucherOrder.setVoucherId(voucherId);
//        //2.7 创建阻塞队列
//        orderTasks.add(voucherOrder);
//
//        //3.返回订单id
//        return Result.ok(orderId);
//    }

//    @Override
//    public Result secKillVoucher(Long voucherId) {
//        //1.查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        //2.判断秒杀是否开始
//        LocalDateTime now = LocalDateTime.now();
//        if (voucher.getBeginTime().isAfter(now)) {
//            //尚未开始
//            return Result.fail("秒杀尚未开始！");
//        }
//        //3.判断秒杀是否已经结束
//        if (voucher.getEndTime().isBefore(now)) {
//            //秒杀已经结束
//            return Result.fail("秒杀已经结束！");
//        }
//        //4.判断库存是否充足
//        if (voucher.getStock() < 1) {
//            //库存不足
//            return Result.fail("库存不足");
//        }
//        return createVoucherOrder(voucherId);
//    }
//
//    @Transactional
//    public Result createVoucherOrder(Long voucherId) {
//        //5.一人一单
//        Long userId = UserHolder.getUser().getId();
//        //创建锁对象
//        RLock redisLock = redissonClient.getLock("lock:order:" + userId);
//        //尝试获取锁
//        boolean isLock = redisLock.tryLock();
//        //判断
//        if (!isLock) {
//            //获取锁失败，直接返回失败或重试
//            return Result.fail("不允许重复下单！");
//        }
//        try {
//            //5.1 查询该用户是否买过该优惠券
//            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
//            //5.2 判断是否存在
//            if (count > 0) {
//                //用户已经购买过了
//                return Result.fail("用户已经购买过一次！！");
//            }
//            //6.扣减库存
//            boolean success = seckillVoucherService.update()
//                    .setSql("stock = stock - 1")
//                    .eq("voucher_id", voucherId)
//                    .gt("stock", 0)
//                    .update();
//            if (!success) {
//                //扣减失败
//                return Result.fail("库存不足");
//            }
//            //7.创建订单
//            VoucherOrder voucherOrder = new VoucherOrder();
//            //7.1 订单id
//            long orderId = redisIdWorker.nextId("order");
//            voucherOrder.setId(orderId);
//            //7.2 用户id
//            voucherOrder.setUserId(userId);
//            //7.3 代金券id
//            voucherOrder.setVoucherId(voucherId);
//            this.save(voucherOrder);
//            //8.返回订单ID
//            return Result.ok(orderId);
//        }  finally {
//            //释放锁
//            redisLock.unlock();
//        }
//    }

    /*@Transactional
    public Result createVoucherOrder(Long voucherId) {
        //5.一人一单
        Long userId = UserHolder.getUser().getId();

        //创建锁对象
        SimpleRedisLock redisLock = new SimpleRedisLock(stringRedisTemplate, "order:" + userId);
        //尝试获取锁
        boolean isLock = redisLock.tryLock(1200);
        //判断
        if (!isLock) {
            //获取锁失败，直接返回失败或重试
            return Result.fail("不允许重复下单！");
        }
        try {
            //5.1 查询该用户是否买过该优惠券
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            //5.2 判断是否存在
            if (count > 0) {
                //用户已经购买过了
                return Result.fail("用户已经购买过一次！！");
            }
            //6.扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock - 1")
                    .eq("voucher_id", voucherId)
                    .gt("stock", 0)
                    .update();
            if (!success) {
                //扣减失败
                return Result.fail("库存不足");
            }
            //7.创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            //7.1 订单id
            long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);
            //7.2 用户id
            voucherOrder.setUserId(userId);
            //7.3 代金券id
            voucherOrder.setVoucherId(voucherId);
            this.save(voucherOrder);
            //8.返回订单ID
            return Result.ok(orderId);
        }  finally {
            //释放锁
            redisLock.unlock();
        }
    }*/


//    @Transactional
//    public Result createVoucherOrder(Long voucherId) {
//        //5.一人一单
//        Long userId = UserHolder.getUser().getId();
//        synchronized (userId.toString().intern()) {
//            //5.1 查询该用户是否买过该优惠券
//            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
//            //5.2 判断是否存在
//            if (count > 0) {
//                //用户已经购买过了
//                return Result.fail("用户已经购买过一次！！");
//            }
//            //6.扣减库存
//            boolean success = seckillVoucherService.update()
//                    .setSql("stock = stock - 1")
//                    .eq("voucher_id", voucherId)
//                    .gt("stock", 0)
//                    .update();
//            if (!success) {
//                //扣减失败
//                return Result.fail("库存不足");
//            }
//            //7.创建订单
//            VoucherOrder voucherOrder = new VoucherOrder();
//            //7.1 订单id
//            long orderId = redisIdWorker.nextId("order");
//            voucherOrder.setId(orderId);
//            //7.2 用户id
//            voucherOrder.setUserId(userId);
//            //7.3 代金券id
//            voucherOrder.setVoucherId(voucherId);
//            this.save(voucherOrder);
//            //8.返回订单ID
//            return Result.ok(orderId);
//        }
//    }
}
